package keye.document_manage.util;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import keye.document_manage.main.MainFrame;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class MultipleDataSourceAspectAdvice {
	
	private static final ThreadLocal<String> dataSource = new InheritableThreadLocal<String>();
	
	@Around("execution(* keye.document_manage.dao.mysql.*.*(..))")
	public Object doAround(ProceedingJoinPoint jp)throws Throwable{
		MultipleDataSource.setDatasourceKey(MultipleDataSource.MYSQL);
		MultipleDataSource.setDialect(MultipleDataSource.MYSQL);
		return jp.proceed();
	}
	
	@Around("execution(* keye.document_manage.dao.sqlserver.*.*(..))")
	public Object doAround2(ProceedingJoinPoint jp)throws Throwable{
//		MultipleDataSource.setDatasourceKey(MultipleDataSource.SQLSERVER);
//		MultipleDataSource.setDialect(MultipleDataSource.SQLSERVER);
		
		MultipleDataSource.setDatasourceKey(MultipleDataSource.SQLITE);
		MultipleDataSource.setDialect(MultipleDataSource.SQLITE);
		return jp.proceed();
	}
	
	@Around("execution(* keye.document_manage.dao.sqlite.*.*(..))")
	public Object doAround3(ProceedingJoinPoint jp)throws Throwable{
		MultipleDataSource.setDatasourceKey(dataSource.get());
		MultipleDataSource.setDialect(MultipleDataSource.SQLITE);
		return jp.proceed();
	}
	//M:\test\t
	@Around("execution(* keye.document_manage.service.*.*.pushDatas(..))")
	public Object doAround4(ProceedingJoinPoint jp)throws Throwable{
		Path p = Paths.get((String)jp.getArgs()[5]+File.separator);
		if(Files.notExists(p)){
			Files.createDirectories(p);
		}
		DynamicCreateDataSourceBean dynamicBean = (DynamicCreateDataSourceBean)MainFrame.CONTEXT.getBean("dynamicCreateDataSourceBean");
		String beanKey = String.valueOf(System.nanoTime());
		dynamicBean.addSourceBeanToApp((String)jp.getArgs()[5], beanKey);
		dataSource.set(beanKey);
		
		MultipleDataSource.setDatasourceKey(MultipleDataSource.SQLITE);
		MultipleDataSource.setDialect(MultipleDataSource.SQLITE);
		Object o = jp.proceed();
		dynamicBean.removeBean(beanKey);
		return o;
	}
}
